package com.visec.hdy.sync.ftp.code;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.visec.hdy.sync.ftp.config.FtpSendClient;

public class FtpSendClientTool {
	private volatile int MAX_SIZE;
	private FtpSendClient ftpSendClient;
	private volatile List<FtpSendClient> free;
	private volatile int use;

	public FtpSendClientTool(int mAX_SIZE, FtpSendClient ftpSendClient) {
		super();
		MAX_SIZE = mAX_SIZE;
		use = 0;
		this.ftpSendClient = ftpSendClient;
		this.free=new ArrayList<FtpSendClient>();
	}

	public synchronized FtpSendClient get() {
		if (use < MAX_SIZE) {
			FtpSendClient copy = this.ftpSendClient.copy();
			free.add(copy);
			use++;
		}
		if (free.size() > 0) {
			return free.remove(0);
		} else {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return get();
		}
	}

	public synchronized void back(FtpSendClient ftpSendClient) {
		if (free.size() >= MAX_SIZE) {
			try {
				ftpSendClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}
		free.add(ftpSendClient);
	//	System.out.println("free size:"+free.size());
		notify();
	}
	
	public synchronized void clear(){
		use=0;
		for(int i=free.size()-1;i>=0;i--){
			FtpSendClient f = free.get(i);
			try {
				f.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				
			}
			free.remove(f);
		}
	}

}
